﻿using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SqlSugar.IOC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AyFrame.Dto
{
    class AppSetting
    {
        public AyConnection AyConnection { get; set; }
    }

    public class AyConnection
    {
        public string ConnId { get; set; }

        public string ConnString { get; set; }
        public string DbType { get; set; }
        public IocDbType IocDbType { get; set; }
        public List<AyConnection> Slaves { get; set; }
    }

    public class AppSettingConfig
    {
        static Dictionary<string, IocDbType> _dic = new Dictionary<string, IocDbType>
        {
            ["SqlServer"] = IocDbType.SqlServer,
            ["MySql"] = IocDbType.MySql,
            ["Oracle"] = IocDbType.Oracle
        };

        public static AyConnection AyConnection => GetAyConnection();

        static AyConnection GetAyConnection()
        {
            var path = "appsettings.json";

            var str = File.ReadAllText(path);

            var obj = JsonConvert.DeserializeObject<AppSetting>(str);

            var cfg = obj.AyConnection;

            cfg.IocDbType = _dic[cfg.DbType];
            if (cfg.Slaves != null)
                cfg.Slaves.ForEach(t => t.IocDbType = _dic[t.DbType]);

            return obj.AyConnection;
        }
    }
}
